import 'package:dio/dio.dart';

import 'dio_config.dart';


class DioHelper {
  static final DioHelper _instance = DioHelper._internal();
  factory DioHelper() => _instance;

  DioHelper._internal();

  Dio? _dio;
  SDioConfig? sDioConfig;

  init(SDioConfig baseConfig) {
    sDioConfig ??= baseConfig;
    _dio ??= Dio(baseConfig.getBaseOptions());

  }

  void addInterceptors({Iterable<Interceptor>? iterable}) {
    if (iterable != null) {
      _dio?.interceptors.addAll(iterable);
    }
  }

  Future<dynamic> request(
      String url, {
        dynamic queryParams,
        RequestType method = RequestType.GET,
        bool showLoading = false,
        Map? extra
      }) async {

    if (_dio == null || sDioConfig == null) {
      throw SDioException(100, 'Http is not init');
    }

    // 防止init之后baseUrl改变，重新赋值
    _dio?.options.baseUrl = sDioConfig!.getBaseOptions().baseUrl;

    try {

      Response response;

      switch(method) {
        case RequestType.POST:
          response = await _dio!.post(
            url,
            data: queryParams,
          );
          break;
        default:
          response = await _dio!.get(
            url,
            queryParameters: queryParams,
          );
      }

      return sDioConfig?.onResponse(response.data, {});

    } on DioException catch (e) {
      sDioConfig!.onError(e, extra);
    }

  }


}

enum RequestType {
  POST,
  GET
}
